<template>
    <div class="app-container">

        <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">

            <el-col :span="6">
                <el-form-item label="采购编号:" prop="purchaseNo">
                    <el-input maxlength="30" v-model="queryParams.purchaseNo" clearable
                              placeholder="请输入采购编号"></el-input>
                </el-form-item>
            </el-col>

            <el-col :span="6">
                <el-form-item label="车辆归属城市:" prop="cityName">
                    <city-select v-model="citySelection" placeholder="请选择车辆归属城市" ref="citySelect"
                                 :showAllLevels="false"
                                 @change="citySelectionChange"></city-select>
                </el-form-item>
            </el-col>

            <el-col :span="6">
                <el-form-item label="车辆性质:" prop="carNature">
                    <el-select filterable v-model="queryParams.carNature" clearable>
                        <template v-for="dict in dict.type.car_nature">
                            <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                        </template>
                    </el-select>
                </el-form-item>
            </el-col>

            <el-col :span="6">
                <el-form-item label="车架号:" prop="vinNo">
                    <el-input maxlength="30" v-model="queryParams.vinNo" clearable
                              placeholder="请输入车架号"></el-input>
                </el-form-item>
            </el-col>
            <!--            <el-col :span="6">-->
            <!--                <el-form-item label="行驶证所有人" prop="ownerName">-->
            <!--                    <el-input v-model="queryParams.ownerName" clearable placeholder="请输入行驶证所有人"></el-input>-->
            <!--                </el-form-item>-->
            <!--            </el-col>-->

        </SearchContent>

        <div class="card-wrap card-padding">
            <div class="table-title-wrap justify-end">
                <!--                <el-button type="primary" size="mini" @click="handleTransfer"-->
                <!--                           v-hasPermi="['demo:demo:add']">分配车辆-->
                <!--                </el-button>-->
                <!--                <el-button type="primary" size="mini"-->
                <!--                           v-hasPermi="['purchaseManage:certificateList:batchadd']">批量导入-->
                <!--                </el-button>-->
                <el-button type="success" size="mini" @click="handleExport"
                           v-hasPermi="['purchaseManage:certificateList:export']">导出
                </el-button>
            </div>

            <table-page :loading="loading" :dataList="dataList" border :total="total" :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize" @setSizeCurrent="getList">
                <!-- 操作插槽 -->
                <template slot="tableColAc">
                    <el-table-column label="操作" min-width="150" align="center" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <e-button v-if="scope.row.uploadStatus=='0'" size="mini" type="text"
                                      @click="handleUpload(scope.row)"
                                      v-hasPermi="['purchaseManage:certificateList:upload']">上传合格证
                            </e-button>
<!--                            只有新车待分配、待整备和整备中有编辑按钮-->
                            <e-button v-if="scope.row.uploadStatus=='1' && (scope.row.businessType == '0'||scope.row.businessType == '1'||scope.row.businessType == '2')" size="mini" type="text"
                                      @click="handleUpdate(scope.row)"
                                      v-hasPermi="['purchaseManage:certificateList:edit']">编辑
                            </e-button>
                            <!--                            <e-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"-->
                            <!--                                      v-hasPermi="['demo:demo:remove']">删除-->
                            <!--                            </e-button>-->
                            <e-button size="mini" type="text" @click="handleDetail(scope.row)"
                                      v-hasPermi="['purchaseManage:certificateList:view']">查看
                            </e-button>
                        </template>
                    </el-table-column>
                </template>
                <!-- 普通列插槽 -->
                <template slot="tableCol">
                    <el-table-column min-width="190" show-overflow-tooltip label="合格证编码" align="center"
                                     prop="qualifiedNo">
                        <template slot-scope="scope">
                            {{ scope.row.qualifiedNo|filterNull }}
                        </template>
                    </el-table-column>
                    <el-table-column min-width="255" show-overflow-tooltip label="采购编码" align="center"
                                     prop="purchaseNo">
                        <template slot-scope="scope">
                          <e-button size="mini" type="text" @click="handlePurchaseNo(scope.row)">
                            {{ scope.row.purchaseNo|filterNull }}
                          </e-button>
                        </template>
                    </el-table-column>
                    <el-table-column min-width="200" show-overflow-tooltip label="车架号" align="center">
                        <template slot-scope="scope">
                            {{ scope.row.vinNo|filterNull }}
                        </template>
                    </el-table-column>
                    <el-table-column min-width="320" show-overflow-tooltip label="品牌/车系/车型" align="center">
                        <template slot-scope="scope">
                            {{ scope.row.brandName|filterNull }}/{{ scope.row.seriesName|filterNull }}/{{ scope.row.modelName|filterNull }}
                        </template>
                    </el-table-column>
                    <!--                    <el-table-column label="发票编码" align="center" prop="invoiceNo">-->
                    <!--                        <template slot-scope="scope">-->
                    <!--                            {{scope.row.invoiceNo|filterNull}}-->
                    <!--                        </template>-->
                    <!--                    </el-table-column>-->
                    <el-table-column min-width="115" show-overflow-tooltip label="车辆性质" align="center"
                                     prop="carNature">
                        <template slot-scope="scope">
                            <dict-tag
                                :options="dict.type.car_nature"
                                :value="scope.row.carNature"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column min-width="115" show-overflow-tooltip label="车辆归属" align="center"
                                     prop="ascription">
                        <template slot-scope="scope">
                            {{ scope.row.ascription|filterNull }}
                        </template>
                    </el-table-column>
                    <!--                    <el-table-column label="车架号" align="center" prop="vinNo">-->
                    <!--                        <template slot-scope="scope">-->
                    <!--                            {{scope.row.vinNo|filterNull}}-->
                    <!--                        </template>-->
                    <!--                    </el-table-column>-->
                    <!--                    <el-table-column label="车辆运营" align="center" prop="operationsName">-->
                    <!--                        <template slot-scope="scope">-->
                    <!--                            {{scope.row.operationsName|filterNull}}-->
                    <!--                        </template>-->
                    <!--                    </el-table-column>-->
                    <el-table-column min-width="190" show-overflow-tooltip label="操作人" align="center"
                                     prop="updateBy">
                        <template slot-scope="scope">
                            {{ scope.row.updateBy|filterNull }}
                        </template>
                    </el-table-column>
                    <el-table-column min-width="150" show-overflow-tooltip label="操作时间" align="center"
                                     prop="updateTime">
                        <template slot-scope="scope">
                            {{ scope.row.updateTime|filterNull }}
                        </template>
                    </el-table-column>
                </template>
            </table-page>

        </div>


        <!-- 添加或修改测试单表对话框 -->
        <el-dialog :title="title" :visible.sync="open" append-to-body width="45%">
            <el-form ref="form" :rules="rules" :model="form" label-width="120px">

                <el-row>
                    <el-col :span="20">
                        <el-form-item label="行驶证所有人:" prop="ownerId">
                            <el-select ref="deptselect" @click.native="deptClick" v-model="form.ownerId"
                                       style="width: 100%">
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="20">
                        <el-form-item label="备注:" prop="remark">
                            <el-input v-model="form.remark" maxlength="500"
                                      type="textarea"
                                      :rows="2"
                                      clearable placeholder="请输入备注"></el-input>

                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer">
                <el-button @click="cancel">{{ isNew ? '取消' : '关闭' }}</el-button>
                <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="isNew">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog
            title="选择组织"
            :visible.sync="dialogVisible"
            width="35%">
            <div class="head-container">
                <el-tree
                    :data="deptOptions"
                    :props="defaultProps"
                    :expand-on-click-node="false"
                    :filter-node-method="filterNode"
                    ref="tree"
                    node-key="id"
                    default-expand-all
                    highlight-current
                    @node-click="handleNodeClick"
                />
            </div>
        </el-dialog>

    </div>
</template>

<script>
import SearchContent from "@/components/SearchContent/index.vue";
import {qualifiedCardDelete, qualifiedCardDistribute, qualifiedCardList} from "@/api/purchaseManage/certificateList";
import {deptTreeSelect, listUser} from "@/api/system/user";
import CitySelect from "@/views/components/citySelect.vue";

export default {
    name: "CertificateList",
    components: {
        CitySelect,
        SearchContent
    },
    dicts: ['car_nature'],
    data() {
        return {
            citySelection: [],
            dialogVisible: false,
            deptOptions: null,
            defaultProps: {
                children: "children",
                label: "label"
            },
            deptLabel: '',
            //按钮loading
            buttonLoading: false,
            // 遮罩层
            loading: true,
            isNew: true,
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                purchaseNo: null,
                cityName: null,
                carNature: null,
                ownerName: null,
                vinNo: null,
            },

            total: 0,
            dataList: [],
            userList: [],
            selQualifiedCardId: '',
            // 表单参数
            form: {
                followerIds: null,
                transferMemo: null,
            },
            // 表单校验
            rules: {
                ownerId: [
                    {required: true, message: "行驶证所有人不能为空", trigger: "change"}
                ],
            }
        };
    },
    created() {
        this.getList()
        // this.getDeptTree()
        // this.getUserList()
    },
    activated() {
        this.getList()
    },
    methods: {
        /** 查询测试单表列表 */
        getList() {
            this.loading = true;


            qualifiedCardList(this.queryParams).then(res => {
                if (res.code == "200") {
                    const {rows, total} = res
                    this.dataList = rows
                    this.total = total
                    this.loading = false;
                }

            });
        },
        citySelectionChange(val) {
            if (val.length > 0) {
                const nodes = Array.from(val, item => ({
                    value: item.value,
                    label: item.label,
                    pv: item.parent.value,
                    pl: item.parent.label
                }))
                this.queryParams.belongCityName = nodes[0].label
                this.citySelection = [nodes[0].pv, nodes[0].value]

            } else {
                this.citySelection = val

                this.queryParams.belongCityName = ""
            }

        },

        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        /** 查询组织下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then(response => {
                this.deptOptions = response.data;
            });
        },
        // 节点单击事件
        handleNodeClick(data) {
            console.log('data', data)

            this.deptLabel = data.label
            this.deptId = data.id;
            // this.form.followerIds = null;

            this.dialogVisible = false;

            this.getUserList();
        },
        getUserList() {
            listUser({
                pageNum: 1,
                pageSize: 100000,
                deptId: this.deptId
            }).then(response => {
                    this.userList = response.rows;
                    // this.total = response.total;
                    // this.loading = false;
                }
            );
        },
        deptClick() {
            this.dialogVisible = true

            this.$refs.deptselect.blur()
        },

        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                followerIds: null,
                transferMemo: null,
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },

        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10,
                purchaseNo: null,
                cityName: null,
                carNature: null,
                ownerName: null,
                vinNo:null
            },
                this.citySelection = []
            // this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('/qualifiedCard/export', {
                ...this.queryParams
            }, `合格证列表.xlsx`)
        },
        /** 上传合格证 */
        handleUpload(row) {
            this.$router.push({
                name: 'CertificateAdd',
                query: {qualifiedCardId: row.qualifiedCardId, pageType: '上传合格证'}
            })
        },

        /** 分配车辆 */
        handleTransfer(row) {
            // this.$modal.msgError("开发中")

            this.selQualifiedCardId = row.qualifiedCardId;
            this.reset();
            this.open = true;
            this.title = "分配车辆";

        },

        handleDetail(row) {
            this.$router.push({
                name: 'CertificateDetail',
                query: {qualifiedCardId: row.qualifiedCardId, pageType: '合格证详情'}
            })
        },

        handlePurchaseNo(row){
            if ( Number(row?.purchaseSource) === 2 ) {
            //订单
                this._toPage({
                    name: 'OrderPurchase',
                    query: {purchaseOrderId: row.purchaseOrderId, type: 'detail', pageType: '订单采购详情'}
                })
           } else {
                this._toPage({
                name: 'PurchaseAdd',
                query: {purchaseOrderId: row.purchaseOrderId, type: 'detail', pageType: '采购详情'}
              })
          }
        },



        /** 修改按钮操作 */
        handleUpdate(row) {
            this.$router.push({
                name: 'CertificateAdd',
                query: {qualifiedCardId: row.qualifiedCardId, pageType: '编辑合格证'}
            })
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            this.$modal.confirm('确定删除？').then(() => {
                this.loading = true;
                return qualifiedCardDelete(row.qualifiedCardId);
            }).then(() => {
                this.loading = false;
                this.handleQuery();
                this.$modal.msgSuccess("删除成功");
            }).finally(() => {
                this.loading = false;
            });
        },

        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    this.buttonLoading = true;

                    qualifiedCardDistribute({
                        ...this.form,
                        qualifiedCardId: this.selQualifiedCardId
                    }).then(res => {
                        this.buttonLoading = false;
                        this.$modal.msgSuccess("提交成功");
                        this.open = false;
                        this.handleQuery();
                    }).finally(() => {
                        this.buttonLoading = false;
                    });
                }
            });
        },

    }
};
</script>


<style lang="scss" scoped>
.pagination-container {
    padding: 0 20px 50px !important;
}


.form-dialog {
    ::v-deep .el-dialog__header {
        padding: 10px 20px;
        border-bottom: 1px solid #DCDFE6;

        .el-dialog__headerbtn {
            top: 15px;
        }
    }

    .box-card {
        margin-bottom: 20px;

        .card-title {
            font-size: 16px;
            position: relative;
            margin-left: 8px;
            padding: 0;
        }

        .card-title::after {
            content: '';
            width: 4px;
            height: 18px;
            background-color: aqua;
            display: block;
            position: absolute;
            left: -12px;
            top: 2px;
        }
    }

}
</style>
